package org.ravenhearte.hardboild.assets;

import java.util.LinkedList;

import org.ravenhearte.hardboild.gamelogic.*;

import com.jme.math.FastMath;
import com.jme.math.Vector3f;
import com.jme.scene.Controller;

public class WalkController extends Controller {
	private static final long serialVersionUID = 6978521469032371545L;
	
	private static final float heightAdjust = 1;
	
	private GameCharacter character;
	private LinkedList<GameTile> path;

    public WalkController(GameCharacter character, LinkedList<GameTile> path) {
    	this.character = character;
    	this.path = path;
    	
		GameTile destTile = path.getFirst();
        Vector3f thisPos = character.getSpatial().getLocalTranslation();
        Vector3f destination = destTile.getWorldLocation().clone();
        Vector3f direction = destination.subtract(thisPos);
        direction.normalizeLocal();
        
        float angle = FastMath.atan2(direction.y, direction.x)
        	- FastMath.atan2(0, 0);
        if(angle < 0) {
	        angle += Math.PI * 2;
        }
        
        character.setDirection(angle);
    }

	@Override
	public void update(float time) {		
		GameTile destTile = path.getFirst();
        Vector3f thisPos = character.getSpatial().getLocalTranslation();
        Vector3f destination = destTile.getWorldLocation().clone();
        
        if(thisPos.distance(destination) < heightAdjust) {
        	thisPos.z = destination.z;
        	character.getSpatial().setLocalTranslation(thisPos);
        }
        else {
        	destination.z = thisPos.z;
        }
        
        if (thisPos.distance(destination) < .03) {
        	character.getSpatial().setLocalTranslation(destination);
        	path.removeFirst();
    		if(path.isEmpty()) {
                character.getSpatial().removeController(this);
                return;
    		}
    		else {
    			destTile = path.getFirst();
    	        thisPos = character.getSpatial().getLocalTranslation();
    	        destination = destTile.getWorldLocation().clone();
    	        Vector3f direction = destination.subtract(thisPos);
    	        direction.normalizeLocal();
    	        
    	        float angle = FastMath.atan2(direction.y, direction.x)
    	        	- FastMath.atan2(1, 0);
    	        if(angle < 0) {
        	        angle += Math.PI * 2;
    	        }
    	        
    	        character.setDirection(angle);
    		}
        }
        else {
            Vector3f direction = destination.subtract(thisPos);
            direction.normalizeLocal();
        	thisPos.addLocal(direction.mult(time * 1));
        	character.getSpatial().setLocalTranslation(thisPos);
        }
	}

}
